<template>
  <view class="wsClassroom-detail-page" :style="{ paddingTop: `${totalNavigationHeight * 2}rpx` }">
    <NavigationBar navigation-title="详情" :go-back="goBack" />
    <view class="detail-header">
      <view class="header-box">
        <template v-if="isVideo">
          <video id="microClassroomVideo" class="header-img" :src="`https://shuyutk.oss-cn-qingdao.aliyuncs.com${chooseItem?.fileUrl}`" :autoplay="true" controls @fullscreenchange="handleFullScreen" @timeupdate="timeupdate" @ended="handleVideoEnd" />
          <image class="header-icon" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/icon_screen.png" @click="handleScreen" />
        </template>
        <template v-else>
          <image class="header-img" mode="aspectFill" :src="`https://shuyutk.oss-cn-qingdao.aliyuncs.com${chooseItem?.coverPic}`" />
          <view class="header-process">
            <view class="active" :style="{ width: `${(audioCurrentTime / audioDuration) * 618}rpx` }" />
          </view>
          <view class="header-control">
            <text class="header-text">
              {{ formatDuration(audioCurrentTime) }}
            </text>
            <view class="header-btn" @click="handlePlay()">
              <image class="btn-img" :src="`https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/${isPlay ? 'pause' : 'play'}_icon.png`" />
            </view>
            <text class="header-text">
              {{ formatDuration(audioDuration) }}
            </text>
          </view>
        </template>
      </view>
      <view class="detail-info">
        <text class="info-type">
          {{ chooseItem?.wisdomType === 1 ? '智商' : chooseItem?.wisdomType === 2 ? '情商' : chooseItem?.wisdomType === 3 ? '财商' : chooseItem?.wisdomType === 4 ? '逆商' : '语商' }}
        </text>
        <text class="info-name">
          {{ chooseItem?.title }}
        </text>
      </view>
    </view>

    <view class="detail-content">
      <view class="detail-tab">
        <view class="tab-item" :class="{ active: tabIndex === 0 }" @click="tabIndex = 0">
          介绍
        </view>
        <view class="tab-item tab-right" :class="{ active: tabIndex === 1 }" @click="tabIndex = 1">
          合集
        </view>
      </view>

      <view v-if="tabIndex === 0" class="tab-content">
        <view class="content-title">
          “五商润育课”课程特色
        </view>
        <view class="content-text">
          1.满足新时代“全人培养”要求:新时代的教育理念强调“全人培养”，即注重孩子的全面发展，包括智力、情感、社交、认知等多方面的提升。通过“五商润育”特色课程，在阅读中培养孩子的智商、语商、情商、逆商、财商。
        </view>
        <view class="content-text">
          2.增加托管竞争优势:在托管市场竞争日益激烈的背景下，托管机构可通过“五商润育”特色课程的差异化服务提升竞争力。
        </view>
        <view class="content-text">
          3.引流刊物增订:“五商润育”特色课程与少儿刊物相辅相成，可以通过课程刺激刊物的增订，提升机构的综合影响力。
        </view>
      </view>

      <scroll-view v-else scroll-y="auto" class="tab-list" @scrolltolower="scrolltolower">
        <view v-for="item in detailList" :key="item.detailId" class="ws-classroom-item" @click="handleChoose(item)">
          <view class="item-lfet">
            <image class="item-img" :src="`https://shuyutk.oss-cn-qingdao.aliyuncs.com${item.coverPic}`" mode="aspectFill" />
            <view class="item-time">
              {{ item.videoDuration }}
            </view>
          </view>
          <view class="item-content">
            <text class="item-name" :class="chooseItem?.detailId === item.detailId && 'item-name-play'">
              {{ item.title }}
            </text>
            <view class="item-progress">
              <text class="item-type">
                {{ item.wisdomType === 1 ? '智商' : item.wisdomType === 2 ? '情商' : item.wisdomType === 3 ? '财商' : item.wisdomType === 4 ? '逆商' : '语商' }}
              </text>
              <text class="item-date">
                {{ getText(item) }}
              </text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <Confirm v-model:show-confrim="showConfrim" v-model:show-finish="showFinish" :text="chooseItem?.wisdomType === 1 ? '智商' : chooseItem?.wisdomType === 2 ? '情商' : chooseItem?.wisdomType === 3 ? '财商' : chooseItem?.wisdomType === 4 ? '逆商' : '语商'" @continue="handleContinue" />
  </view>
</template>

<script lang="ts" setup>
import Confirm from './components/confirm.vue';
import { getFiveWisdomDetail } from '@/api/wsClassroom/index';
import type { GetFiveWisdomDetailParams, GetFiveWisdomDetailResult } from '@/api/wsClassroom/type';
import { updateProgress } from '@/api/common/index';
import type { UpdateProgressParams } from '@/api/common/type';
import { formatDuration } from '@/utils/common/index';
import { getNavigationHeight } from '@/utils/auth';
import { useUserStore } from '@/store';

const userStore = useUserStore();
const totalNavigationHeight = ref(getNavigationHeight());

// TODO: 投屏
const tabIndex = ref<number>(1);

let videoContext: any; // 视频实例
onReady(() => {
  videoContext = uni.createVideoContext('microClassroomVideo');
});

const pageParams: GetFiveWisdomDetailParams = {
  pageNum: 1,
  pageSize: 10,
  detailId: '',
};
const detailList = ref<Array<GetFiveWisdomDetailResult>>([]);
const total = ref<number>(0);
const chooseItem = ref<GetFiveWisdomDetailResult>();
const currentDate = ref<string>('');

const getText = (item: GetFiveWisdomDetailResult) => {
  const textList = ['一', '二', '三', '四', '五', '六', '日'];
  return `${currentDate.value} 第${textList[Math.max(item.week - 1, 0)]}周 周${textList[Math.max(item.dayOfWeek - 1, 0)]}`;
};

const isVideo = computed(() => {
  if (!chooseItem.value)
    return false;
  return chooseItem.value?.fileUrl.indexOf('mp4') > -1;
});

// 音频
const isPlay = ref<boolean>(false);
const audioCurrentTime = ref<number>(0);
const audioDuration = ref<number>(0);
const audioProcess = ref<number>(0);
let audioContext: any;
const handlePlay = (url?: string) => {
  if (url) {
    audioContext?.destroy();
    audioCurrentTime.value = 0;
    audioDuration.value = 0;
    audioProcess.value = 0;
    isPlay.value = false;

    audioContext = uni.createInnerAudioContext();
    audioContext.src = `https://shuyutk.oss-cn-qingdao.aliyuncs.com${url}`;
    audioContext.onPlay(() => {
      isPlay.value = true;
    });
    audioContext.onPause(() => {
      isPlay.value = false;
    });
    audioContext.onEnded(() => { //  播放结束
      isPlay.value = false;
    });
    audioContext.onTimeUpdate(() => { //  播放结束
      audioCurrentTime.value = Math.round(audioContext.currentTime);
      audioDuration.value = Math.round(audioContext.duration);
      audioProcess.value = Math.round((audioCurrentTime.value / audioDuration.value) * 100);
      audioProcess.value = Math.min(audioProcess.value, 100);
    });
  }
  if (!tabIndex.value)
    return;
  if (isPlay.value) {
    audioContext?.pause();
  }
  else {
    audioContext?.play();
  }
};

const handleChoose = (item: GetFiveWisdomDetailResult) => {
  if (item.detailId === chooseItem.value?.detailId)
    return;
  chooseItem.value = item;

  if (!isVideo.value)
    handlePlay(item.fileUrl);
};

const getDetail = () => {
  getFiveWisdomDetail(pageParams).then((res: { rows: Array<GetFiveWisdomDetailResult>; total: number }) => {
    detailList.value = detailList.value.concat(res.rows);
    total.value = res.total;
    if (chooseItem.value)
      return;
    const item = detailList.value.find((item: GetFiveWisdomDetailResult) => item.detailId === pageParams.detailId);
    if (item) {
      handleChoose(item);
    }
    else {
      handleChoose(detailList.value[0]);
    }
  });
};

const scrolltolower = () => {
  if (total.value <= detailList.value.length)
    return;
  pageParams.pageNum++;
  getDetail();
};

onLoad((option: any) => {
  pageParams.detailId = option.id;
  currentDate.value = option.date;
  getDetail();
});

const currentTime = ref(0);
const videoProcess = ref(0);
// 播放进度
const timeupdate = (e: any) => {
  currentTime.value = e.detail.currentTime;
  videoProcess.value = Math.round((currentTime.value / e.detail.duration) * 100);
  videoProcess.value = Math.min(videoProcess.value, 100);
};

const handleUpdateProgress = () => {
  if (!chooseItem.value || chooseItem.value.progress >= 100)
    return;
  const params: UpdateProgressParams = {
    type: 1,
    courseId: chooseItem.value.courseId,
    courseDetailId: chooseItem.value.detailId,
    courseDetailTitle: chooseItem.value.title,
    progress: chooseItem.value.progress >= 100 ? 100 : isVideo.value ? videoProcess.value : audioProcess.value,
    wisdomType: chooseItem.value.wisdomType,
  };
  if (params.progress >= 100)
    chooseItem.value.progress = 100;
  updateProgress(params);
};

onUnload(() => {
  handleUpdateProgress();
  audioContext?.destroy();
  videoContext?.pause();
});

// TODO: 投屏
const handleScreen = () => {

  // videoContext.requestFullScreen({ direction: 90 });
};
const showConfrim = ref<boolean>(false); // 退出
const showFinish = ref<boolean>(false); // 结束
const handleContinue = () => {
  if (isVideo.value) {
    videoContext?.play();
  }
  else {
    audioContext?.play();
  }
};
// 全屏
let fullScreen: boolean = false;
const handleFullScreen = (e: any) => {
  fullScreen = e.detail.fullScreen;
};
const handleVideoEnd = () => {
  if (fullScreen) {
    videoContext.requestFullScreen({ direction: 0 });
    videoContext.exitFullScreen();
  }
  if (chooseItem.value && chooseItem.value?.progress >= 100)
    return;
  handleUpdateProgress();
  showFinish.value = true;
};

const goBack = () => {
  if (isVideo.value) {
    videoContext?.pause();
  }
  else {
    audioContext?.pause();
  }
  if (chooseItem.value && chooseItem.value?.progress >= 100) {
    uni.navigateBack();
    return;
  }
  showConfrim.value = true;
};

// 分享
uni.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
});
onShareAppMessage(() => {
  return {
    title: userStore.share_txt,
    imageUrl: userStore.share_pic_url,
  };
});
</script>

<style lang="scss" scoped>
.wsClassroom-detail-page {
  height: 100%;
  display: flex;
  flex-direction: column;

  .detail-header {
    display: flex;
    flex-direction: column;
    background: #fff;

    .header-box {
      position: relative;
      width: 750rpx;
      height: 422rpx;
      padding-top: 190rpx;
      display: flex;
      flex-direction: column;
      align-items: center;

      .header-img {
        position: absolute;
        top: 0;
        left: 0;
        width: 750rpx;
        height: 422rpx;
      }

      .header-icon {
        position: absolute;
        top: 160rpx;
        right: 20rpx;
        width: 64rpx;
        height: 64rpx;
      }

      .header-process {
        position: relative;
        width: 618rpx;
        height: 10rpx;
        background: #fff;
        border-radius: 5rpx;
        display: flex;

        .active {
          height: 10rpx;
          border-radius: 5rpx;
          background: #0BC196;
        }
      }

      .header-control {
        position: relative;
        width: 538rpx;
        padding-top: 40rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header-text {
          font-size: 24rpx;
          color: #37CC67;
        }

        .header-btn {
          width: 104rpx;
          height: 104rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #fff;

          .btn-img {
            width: 36rpx;
            height: 40rpx;
          }
        }
      }
    }

    .detail-info {
      padding: 24rpx 40rpx;
      display: flex;
      align-items: center;

      .info-type {
        padding: 0 16rpx;
        font-size: 20rpx;
        line-height: 34rpx;
        background: #FFEED1;
        color: #FF9532;
      }

      .info-name {
        flex: 1;
        padding-left: 16rpx;
        font-size: 36rpx;
        color: #251504;
        line-height: 54rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  .detail-content {
    flex: 1;
    overflow: hidden;
    padding: 24rpx 40rpx 0;
    margin-top: 24rpx;
    background: #fff;

    display: flex;
    flex-direction: column;

    .detail-tab {
      display: flex;
      margin-bottom: 40rpx;

      .tab-item {
        padding-bottom: 8rpx;
        font-size: 32rpx;
        color: #000000;
        line-height: 48rpx;
      }

      .tab-right {
        margin-left: 64rpx;
      }

      .active {
        font-weight: bold;
        color: #0BC196;
        border-bottom: 4rpx solid #0BC196;
      }
    }

    .tab-content {
      flex: 1;
      overflow: auto;

      .content-title {
        font-weight: bold;
        font-size: 28rpx;
        color: #251504;
        line-height: 42rpx;
      }

      .content-text {
        padding-top: 28rpx;
        font-size: 28rpx;
        color: #87837B;
        line-height: 42rpx;
      }

      .content-text:last-child {
        margin-bottom: 40rpx;
      }
    }

    .tab-list {
      flex: 1;
      overflow: auto;

      .ws-classroom-item {
        padding: 28rpx 0;
        display: flex;
        align-items: center;
        border-bottom: 2rpx solid #EDEDED;

        .item-lfet {
          position: relative;
          width: 200rpx;
          height: 113rpx;
          border-radius: 8rpx;
          overflow: hidden;

          .item-img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
          }

          .item-time {
            position: absolute;
            bottom: 0;
            right: 0;

            padding: 0 8rpx;
            background: rgba(0,0,0,0.6);
            border-radius: 8rpx 0 8rpx 0;
            font-size: 20rpx;
            color: #FFFFFF;
            line-height: 30rpx;
          }
        }

        .item-content {
          flex: 1;
          padding-left: 24rpx;
          display: flex;
          flex-direction: column;

          .item-name {
            font-weight: bold;
            font-size: 28rpx;
            color: #251504;
            line-height: 42rpx;
          }

          .item-name-play {
            color: #37CC67;
          }

          .item-progress {
            display: flex;
            align-items: center;
            padding-top: 12rpx;
            font-size: 24rpx;
            line-height: 36rpx;

            .item-type {
              padding: 0 16rpx;
              font-size: 20rpx;
              line-height: 34rpx;
              background: #FFEED1;
              color: #FF9532;
            }

            .item-date {
              padding-left: 16rpx;
              font-size: 24rpx;
              color: #87837B;
              line-height: 36rpx;
            }
          }
        }
      }

      .ws-classroom-item:last-child {
        border-bottom: 2rpx solid #EDEDED;
        margin-bottom: 40rpx;
      }
    }
  }
}
</style>
